//
//  ClassViewController.m
//  GiftItems
//
//  Created by lanou3g on 15/9/18.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "ClassViewController.h"
#import "SelectView.h"
#import "DidGiftView.h"
#import "SelectModel.h"
#import "SelectCollectionViewCell.h"
#import "ClassCollectionReusableView.h"
#import "DidGiftCollectionViewCell.h"
#import "VerticalButtonControl.h"
#import "LORefresh.h"
#import "DIYTableViewController.h"
#import "SpecialDetailsTableViewController.h"
#import "DIYCatgModel.h"
#import "WebViewController.h"
#import "MJRefresh.h"
@interface ClassViewController ()
//<MJRefreshBaseViewDelegate>

//精心挑选 - 四个类的名字
@property (nonatomic, strong) NSMutableArray *titleArray;
////精心选礼 - 每个大分类中的小分类
@property (nonatomic, strong) NSMutableArray *classArray;
//分段控件,控制创建视图 + 数据解析
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
//精心挑选 页面
@property (nonatomic, strong) SelectView *selectView;
//DIY礼 页面
@property (nonatomic, strong) DidGiftView *didGiftView;
//自定义的控制对象(侧边按钮)
@property (nonatomic, strong) VerticalButtonControl *verticalControl;
////分类 - DIY礼 - 热门工艺数组
@property (nonatomic, strong) NSMutableArray *array;
//用于刷新数据(上拉刷新,下拉加载)
@property (nonatomic) NSInteger count;
@property (nonatomic, strong) NSString *Url;
//分类 - DIY礼 - 存放除了 "热门" 以外的数据
@property (nonatomic, strong) NSMutableArray *stepArray;
//拼接链接,以便刷新数据
@property (nonatomic, strong) NSString *lastid;
@property (nonatomic) BOOL isSelect;
//加载动画
@property (nonatomic,strong) YYAnimationIndicator *animationLoad;
//分类 - DIY礼 - 点击分段控制器 进入的次数
@property (nonatomic) NSInteger time;
@end

@implementation ClassViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //进入程序,初始化 用于计数 的变量
    self.count = 0;
    self.time = 0;
    
    self.isSelect = NO;
    //创建segmentContro
    [self segmentContro];
    
    
    //创建  精心挑礼页面
    [self pickGift];
    //精心挑礼  数据解析
    [self dataAnalysisWithurl];
    
    
    //DIY页面搭建 -- 集合视图
    [self diyGiftByHand];
    self.didGiftView.hidden = YES;
    self.didGiftView.userInteractionEnabled = YES;
    
    
    //DIY页面搭建 -- 侧边控制
    [self loadVerticalControlView];
    self.verticalControl.hidden = YES;
//    //数据解析 - DIY礼 - 热门工艺
//    [self analysisWithUrlAndCount:self.count];
    
    //数据刷新
    [self addHeader];
    [self addFooter];
}
//上拉加载数据
- (void)addHeader{
    __unsafe_unretained typeof(self) vc = self;
    //添加下拉刷新头部控件
    [self.didGiftView.collectionV addHeaderWithCallback:^{
        [vc.stepArray removeAllObjects];
        if (!vc.isSelect) {
            [vc analysisWithUrlAndCount:0];
        }else {
            [vc analysisAboutLastid:[NSString stringWithFormat:@"nil"]];
        }
        [vc.didGiftView.collectionV reloadData];
        [vc.didGiftView.collectionV headerEndRefreshing];
    }];
    //自动刷新 -- 一进入程序就下拉刷新
    //[self.didGiftView.collectionV headerBeginRefreshing];
}
//下拉刷新
- (void)addFooter{
    __unsafe_unretained typeof(self) vc = self;
    [self.didGiftView.collectionV addFooterWithCallback:^{
        if (!vc.isSelect) {
            vc.count++;
            [vc analysisWithUrlAndCount:vc.count];
        }else {
            [vc analysisAboutLastid:vc.lastid];
        }
        
        [vc.didGiftView.collectionV reloadData];
        [vc.didGiftView.collectionV footerEndRefreshing];
    }];
}
//创建segmentControl
- (void)segmentContro{
    NSArray *array = @[@"精心挑礼", @"DIY礼"];
    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:array];
    self.segmentedControl.frame = CGRectMake(0, 0, 200, 30);
    self.segmentedControl.selectedSegmentIndex = 0;
    self.segmentedControl.tintColor = [UIColor whiteColor];
    //设置在 选中状态 下的字体和颜色
    NSDictionary *selectTextAttribute = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:13],NSForegroundColorAttributeName:[UIColor colorWithRed:255.0 / 255 green:151.0 / 255 blue:255.0 / 255 alpha:1.0]};
    //将设置好的字体和颜色 设置为segment标题的属性
    [self.segmentedControl setTitleTextAttributes:selectTextAttribute forState:(UIControlStateSelected)];
    
    
    //不选中状态 的字体和颜色
    NSDictionary *unselectTextAttribute = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:13],NSForegroundColorAttributeName:[UIColor whiteColor]};
    //将字体和颜色加在title上
    [self.segmentedControl setTitleTextAttributes:unselectTextAttribute forState:(UIControlStateNormal)];
    [self.segmentedControl addTarget:self action:@selector(Build:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = self.segmentedControl;
}
//实现 点击分段控件 的方法
- (void)Build:(UISegmentedControl *)seg{
    if (seg.selectedSegmentIndex == 0) {
        self.selectView.hidden = NO;
        self.didGiftView.hidden = YES;
        self.verticalControl.hidden = YES;
    }else if (seg.selectedSegmentIndex == 1) {
        self.selectView.hidden = YES;
        self.didGiftView.hidden = NO;
        self.verticalControl.hidden = NO;
        if (self.time == 0) {
            [self addAniamtion];
            //数据解析 - DIY礼 - 热门工艺
            [self analysisWithUrlAndCount:self.count];
            self.time ++;
        }
    }
}
//创建 精心挑礼 页面
- (void)pickGift{
    self.selectView = [[SelectView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
    //注册 集合视图
    self.selectView.ClassificationCV.dataSource = self;
    self.selectView.ClassificationCV.delegate = self;
     
    self.selectView.ClassificationCV.tag = 1000001;
    [self.selectView.ClassificationCV registerClass:[SelectCollectionViewCell class] forCellWithReuseIdentifier:@"MyCell"];
    //注册 增广视图
    [self.selectView.ClassificationCV registerClass:[ClassCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyView"];
    
    [self.view addSubview:self.selectView];
}
//数据解析 - 精心选礼
- (void)dataAnalysisWithurl{
    [self addAniamtion];
    [LORequestManger GET:KChannelUrl success:^(id response) {
        NSDictionary *Dic = (NSDictionary *)response;
        NSDictionary *dictionary = Dic[@"data"];
        for (NSDictionary *dic in dictionary[@"channel_groups"]) {
            [self.titleArray addObject:dic[@"name"]];
            //存放小分类里的数据
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *modelDic in dic[@"channels"]) {
                SelectModel *model = [SelectModel shareWithDictionary:modelDic];
                [array addObject:model];
            }
            [self.classArray addObject:array];
        }
        [self.selectView.ClassificationCV reloadData];
        [self.animationLoad stopAnimationWithLoadText:@"finish" withType:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}
//精心选礼 - 四个大标题
- (NSMutableArray *)titleArray{
    if (!_titleArray) {
        _titleArray = [[NSMutableArray alloc] init];
    }
    return _titleArray;
}
//精心选礼 - 每个大分类中的小分类
- (NSMutableArray *)classArray{
    if (!_classArray) {
        _classArray = [[NSMutableArray alloc] init];
    }
    return _classArray;
}
//增广视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    ClassCollectionReusableView *classReusableV = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyView" forIndexPath:indexPath];
    NSString *title = self.titleArray[indexPath.section];
    [classReusableV setTitleNameWithString:title];
    return classReusableV;
}
//设置增广视图的宽度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (collectionView.tag == 1000001) {
        return CGSizeMake(0,25);
    }
    return CGSizeMake(0, 0);
}
//集合视图的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView.tag == 1000001) {
        NSArray *array = self.classArray[section];
        return array.count;
    }else {
        if (!self.isSelect) {
            return self.array.count;
        }else {
            return self.stepArray.count;
        }
    }
}
//分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (collectionView.tag == 1000001) {
        return self.classArray.count;
    }else {
        return 1;
    }
}
//创建cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView.tag == 1000001) {
        SelectCollectionViewCell *selectCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
        NSArray *array = self.classArray[indexPath.section];
        SelectModel *model = array[indexPath.row];
        [selectCell setValueW:model];
        return selectCell;
    }else {
        DidGiftCollectionViewCell *cell = [self.didGiftView.collectionV dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
        if (!self.isSelect) {
            DidGiftModel *model = self.array[indexPath.row];
            [cell setValueWith:model];
        }else {
            DIYCatgModel *model = self.stepArray[indexPath.row];
            cell.nameLable.text = model.subject;
            [cell.picImage sd_setImageWithURL:[NSURL URLWithString:model.host_pic_ss] placeholderImage:[UIImage imageNamed:@"占位图.jpg"]];
        }
        return cell;
    }
}

//////////////////////////////////////////////////////////////////////////////////////
//创建 DIY礼 页面
- (void)diyGiftByHand{
    self.didGiftView = [[DidGiftView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
    self.didGiftView.collectionV.dataSource = self;
    self.didGiftView.collectionV.delegate = self;
    //注册集合视图
    self.didGiftView.collectionV.tag = 1000002;
    [self.didGiftView.collectionV registerClass:[DidGiftCollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
    [self.view addSubview:self.didGiftView];
}
//数据解析 - DIY礼 - 热门工艺
- (void)analysisWithUrlAndCount:(NSInteger)count{
    
    NSString *Formate = [NSString stringWithFormat:@"%ld",count];
    NSString *str = [kHotArtUrl stringByReplacingOccurrencesOfString:@"参数" withString:Formate];
    [LORequestManger GET:str success:^(id response) {
        NSDictionary *Dic = (NSDictionary *)response;
        for (NSDictionary *dic in Dic[@"data"]) {
            DidGiftModel *model = [DidGiftModel shareWithDic:dic];
            [self.array addObject:model];
        }
        [self.didGiftView.collectionV reloadData];
        [self.animationLoad stopAnimationWithLoadText:@"finish" withType:YES];//加载成功
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}
//分类 - DIY礼 - 热门工艺数组
- (NSMutableArray *)array{
    if (!_array) {
        _array = [[NSMutableArray alloc] init];
    }
    return _array;
}
//数据解析 - DIY礼 - 除开 热门工艺类
- (void)analysisAboutLastid:(NSString *)lastid{
 
    NSString *str = [self.Url stringByReplacingOccurrencesOfString:@"参数" withString:lastid];
    [LORequestManger GET:str success:^(id response) {
        NSDictionary *Dic = (NSDictionary *)response;
        NSDictionary *dic = Dic[@"data"];
        self.lastid = dic[@"lastid"];
        for (NSDictionary *dictionary in dic[@"list"]) {
            DIYCatgModel *model = [DIYCatgModel shareWithDictionary:dictionary];
            [self.stepArray addObject:model];
        }
        [self.didGiftView.collectionV reloadData];
        [self.animationLoad stopAnimationWithLoadText:@"finish" withType:YES];//加载成功
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}
//分类 - DIY礼 - 存放除了 "热门" 以外的数据
- (NSMutableArray *)stepArray{
    if (!_stepArray) {
        _stepArray = [[NSMutableArray alloc] init];
    }
    return _stepArray;
}
//创建侧边控制按钮
- (void)loadVerticalControlView{
    self.verticalControl = [[VerticalButtonControl alloc] initWithFrame:CGRectMake(0, 0, 50, kHeight - 64)];
    [self.view addSubview:self.verticalControl];
    
    //给各个按钮添加点击事件
    NSArray *array = @[self.verticalControl.Origami, self.verticalControl.clothArt, self.verticalControl.remake, self.verticalControl.plait, self.verticalControl.clay, self.verticalControl.draw, self.verticalControl.gardening, self.verticalControl.emblazonry];
    for (int i = 0; i < 8; i++) {
        [array[i] addTarget:self action:@selector(actionButton:) forControlEvents:(UIControlEventTouchUpInside)];
    }
}
//按钮点击事件
- (void)actionButton:(UIButton *)button{
    //开始动画
    [self addAniamtion];
    [self.didGiftView.collectionV reloadData];//移除数据,刷新一次,提高用户体验
    NSArray *UrlArray = @[kHotArtUrl, kclothArtUrl, kOrigamiUrl, kPlaitUrl, kClayUrl, kDrawUrl, kFoodUrl, kEmblazonryUrl];
    for (int i = 0; i < 8; i++) {
        if (button.tag == 1000 + i) {
            [button setTitleColor:[UIColor colorWithRed:255.0 / 255 green:151.0 / 255 blue:255.0 / 255 alpha:1.0] forState:UIControlStateNormal];
            button.backgroundColor = [UIColor whiteColor];
            button.alpha = 1.0;
            if (i == 0) {
                self.count = 0;
                [self.array removeAllObjects];
                [self analysisWithUrlAndCount:self.count];
                self.isSelect = NO;
            }else {
                self.Url = UrlArray[i];
                self.lastid = [NSString stringWithFormat:@"nil"];
                [self.stepArray removeAllObjects];
                [self analysisAboutLastid:self.lastid];
                self.isSelect = YES;
            }
        }else {
            UIButton *aButton = (UIButton *)[self.view viewWithTag:1000 + i];
            [aButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            aButton.backgroundColor = [UIColor grayColor];
            aButton.alpha = 0.4;
        }
    }
}

//点击item的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        SpecialDetailsTableViewController *detailTVC = [[SpecialDetailsTableViewController alloc] init];
        NSArray *array = self.classArray[indexPath.section];
        SelectModel *model = array[indexPath.row];
        NSString *newUrl = [KChannelDetailsUrl stringByReplacingOccurrencesOfString:@"参数" withString:[NSString stringWithFormat:@"%@",model.ID]];
        detailTVC.specialDeatilsUrl = newUrl;
        detailTVC.name = @"精心挑礼";
        detailTVC.titleName = model.name;
        [self.navigationController pushViewController:detailTVC animated:YES];
    }else if (self.segmentedControl.selectedSegmentIndex == 1){
        if (!self.isSelect) {
            DIYTableViewController *DIYtvc = [[DIYTableViewController alloc] init];
            DidGiftModel *model = self.array[indexPath.row];
            DIYtvc.blurImg = model.img;
            DIYtvc.albumid = model.albumId;
            [self.navigationController pushViewController:DIYtvc animated:YES];
        }else {
            WebViewController *webVC = [[WebViewController alloc] init];
            DIYCatgModel *model = self.stepArray[indexPath.row];
            webVC.webUrl = model.share_url;
            webVC.type = @"操作步骤";
            [self.navigationController presentViewController:webVC animated:YES completion:nil];
        }
        //结束动画
        [self.animationLoad stopAnimationWithLoadText:@"finish" withType:YES];//加载成功
    }
}

//添加动画(加载动画)
- (void)addAniamtion {
    self.animationLoad = [[YYAnimationIndicator alloc] initWithFrame:CGRectMake(kWidth / 2 - 40, (kHeight - 64 - 49) / 2 - 40, 80, 80)];
    [self.animationLoad setLoadText:@"努力加载中....."];
    [self.view addSubview:self.animationLoad];
    [self.animationLoad startAnimation];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
